package demo.demo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RowListHelper {
	/**
	 *  Helpers for bookshelf adapters
	 */
	
	public static class Row<TYPE,DATA> {
		public final TYPE type;
		public final List<DATA> data;
		public final int maxColumns;
		public Row(TYPE type, List<DATA> data, int maxColumns) {
			super();
			this.type = type;
			this.data = data;
			this.maxColumns = maxColumns;
		}
		@Override
		public String toString() {
			String text = type.toString();
			text += "[";
			for (DATA data2 : data) {
				text += data2.toString() + ";";
			}
			text += "]";
			return text;
		}
	}
	
	public static class ListRowsBuilder<TYPE,DATA> {
		
		private List<Row<TYPE,DATA>> rows = new ArrayList<Row<TYPE,DATA>>();
		
		public void addRows(List<DATA> data, TYPE type, int columns){
			assert columns != 0 : "columns must be greater zero";
			assert type != null : "type must be not null";
			
			if(data == null || data.isEmpty())
				return;
			
			int cutCount = data.size() / columns;
			cutCount += (data.size() % columns == 0 ? 0 : 1 );
			
			int indexFrom = 0;
			for(int i = 0; i < cutCount; i++){
				int indexTo = Math.min(indexFrom+columns, data.size());
				List<DATA> subList = data.subList(indexFrom, indexTo);
				indexFrom = indexTo;
				rows.add(new Row<TYPE, DATA>(type, subList,columns));
			}
		}
		
		@SuppressWarnings("unchecked")
        public void addRowsWithDivider (List<DATA> data, TYPE type, int columns, TYPE typeDivider ){
			assert columns != 0 : "columns must be greater zero";
			assert type != null : "type must be not null";
			assert typeDivider != null : "typeDivider must be not null";
			
			if(data == null || data.isEmpty())
				return;
			
			rows.add(new Row<TYPE, DATA>(typeDivider, (List<DATA>) Collections.emptyList(), 1));
			addRows(data, type, columns);
		}

		public List<Row<TYPE, DATA>> getRows() {
			return rows;
		}
	}
}
